<template>
  <el-form :model="fruits" :rules="rules" ref="fruitsForm" label-width="100px" class="demo-ruleForm">
    <el-form-item label="名称" prop="name">
      <el-input v-model="fruits.name"></el-input>
    </el-form-item>
    <el-form-item label="销量" prop="sale">
      <el-input v-model.number="fruits.sale"></el-input>
    </el-form-item>
    <el-form-item label="图片" prop="icon">
      <el-input v-model="fruits.icon"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('fruitsForm')">添加</el-button>
      <el-button @click="resetForm()">取消</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
export default {
  data() {
    return {
      fruits: {
        name: '',
        sale: '',
        icon: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        sale: [
          { required: true, message: '请输入销量', trigger: 'blur' },
          { type: 'number', message: '销量必须为数字值' }
        ],
        icon: [
          { required: true, message: '请输入图片地址', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let _this = this
          axios.post("http://localhost:8081/fruit/add",this.fruits).then(function (response){
            if(response.data){
              _this.$alert('添加成功', '添加', {
                confirmButtonText: '确定',
                callback: action => {
                  _this.$router.push('/table')
                }
              });
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      _this.$router.push('/table')
    }
  }
}
</script>